package com.wallace.downloadserver.netty.handler.inbound

import com.wallace.downloadserver.netty.NettyMsg
import com.wallace.downloadserver.util.myJson.JsonUtil
import io.netty.buffer.Unpooled
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.ChannelInboundHandlerAdapter
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component
import java.net.InetSocketAddress

/**
 * 自定义的Handler需要继承Netty规定好的HandlerAdapter
 * 才能被Netty框架所关联，有点类似SpringMVC的适配器模式
 */
@Component
class NettyMsgHandler : ChannelInboundHandlerAdapter() {

    private val log: Logger = LoggerFactory.getLogger(NettyMsgHandler::class.java)

    override fun channelRead(ctx: ChannelHandlerContext, msg: Any) {
        val nettyMsg = msg as? NettyMsg
        log.debug("收到客户端" + ctx.channel().remoteAddress() + "发送的消息：" + nettyMsg)
    }

//    @Throws(Exception::class)
//    override fun channelRead(ctx: ChannelHandlerContext, msg: Objec) {
////        //获取到线程池eventLoop，添加线程，执行
////        ctx.channel().eventLoop().execute {
////            try {
////                //长时间操作，不至于长时间的业务操作导致Handler阻塞
////                Thread.sleep(1000)
////                println("长时间的业务处理")
////            } catch (e: Exception) {
////                e.printStackTrace()
////            }
////        }
//        //获取客户端发送过来的消息
//        log.debug("收到客户端" + ctx.channel().remoteAddress() + "发送的消息：" + nettyMsg)
//        ReferenceCountUtil.release(nettyMsg)
//    }

    @Throws(Exception::class)
    override fun channelReadComplete(ctx: ChannelHandlerContext) {
        log.debug("channelReadComplete")
        val nettyMsg = NettyMsg(type = NettyMsg.NettyMsgType.Default, content = "服务端已收到消息，并给你发送一个问号?")
        val jsonString = JsonUtil.toJson(nettyMsg)
        ctx.writeAndFlush(Unpooled.copiedBuffer(jsonString, Charsets.UTF_8))
    }

    @Throws(Exception::class)
    override fun exceptionCaught(ctx: ChannelHandlerContext, cause: Throwable?) {
        // 发生异常，关闭通道
        log.error(cause?.stackTraceToString())
        ctx.close()
    }
}